package com.example.lovewordsapplication.ui.fragment;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.RecyclerView;

import com.example.lovewordsapplication.MyApplication;
import com.example.lovewordsapplication.R;
import com.example.lovewordsapplication.adapter.WordsAdapter;
import com.example.lovewordsapplication.entity.Words;
import com.example.lovewordsapplication.utils.CommonUtil;
import com.example.lovewordsapplication.utils.OkHttpUtil;
import com.google.gson.Gson;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import jp.wasabeef.recyclerview.animators.SlideInDownAnimator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author Leung
 * @date 2020/4/7 23:37
 */
public class WordsFragment extends Fragment implements
        SwipeRefreshLayout.OnRefreshListener, Callback, View.OnLongClickListener {

    private MyApplication app;
    private Activity activity;
    private SwipeRefreshLayout srlRefresh;
    private RecyclerView rvMessageContainer;
    private WordsAdapter adapter;
    /**
     * 发送状态
     */
    private boolean sendType = true;
    /**
     * 是否是网络获取
     */
    private boolean isNetWork;
    /**
     * 是否是第一次启动
     */
    private boolean isFirstStart = true;
    /**
     * 更新消息的数据源
     */
    private LinkedList<Words.NewslistBean> list = new LinkedList<>();
    /**
     * 读取到本地的数据源
     */
    private List<Words.NewslistBean> beans;

    public WordsFragment(Activity activity) {
        this.activity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_words, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        app = (MyApplication) activity.getApplication();
        // 下拉刷新控件
        srlRefresh = (SwipeRefreshLayout) view.findViewById(R.id.srl_refresh);
        srlRefresh.setColorSchemeResources(R.color.colorPrimary);
        srlRefresh.setOnRefreshListener(this);
        // RecyclerView适配器
        adapter = new WordsAdapter(list);
        // 文本长按事件
        adapter.setTxtOnLongClickListener(this);
        // 消息显示
        rvMessageContainer = (RecyclerView) view.findViewById(R.id.rv_messageContainer);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvMessageContainer.setLayoutManager(manager);
        rvMessageContainer.setAdapter(adapter);
        rvMessageContainer.setItemAnimator(new SlideInDownAnimator());
        rvMessageContainer.getItemAnimator().setAddDuration(500);

    }

    @Override
    public void onStart() {
        super.onStart();
        isNetWork = app.isNetWork();
        if (isFirstStart) {
            String data = CommonUtil.getRawFile(getResources().openRawResource(R.raw.words));
            beans = new Gson().fromJson(data.toString(), Words.class).getNewslist();
            onRefresh();
            isFirstStart = false;
        }
    }

    @Override
    public void onRefresh() {
        if (isNetWork) {
            OkHttpUtil.request(this);
        } else {
            updateData();
        }
        srlRefresh.setRefreshing(false);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Words words = new Gson().fromJson(response.body().string(), Words.class);
        Words.NewslistBean bean = words.getNewslist().get(0);
        sendType = !sendType;
        bean.setSendType(sendType);
        list.addFirst(bean);
        getActivity().runOnUiThread(() -> {
            adapter.notifyItemInserted(0);
            rvMessageContainer.scrollToPosition(0);
        });
    }

    @Override
    public boolean onLongClick(View v) {
        TextView textView = (TextView) v;
        copyContent(textView.getText().toString().trim());
        Toast.makeText(getContext(), "你已成功复制该土味情话了喔！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 复制内容
     *
     * @param text 要复制的文本
     */
    private void copyContent(String text) {
        // 剪贴板管理器
        ClipboardManager clipboardManager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboardManager != null) {
            // 创建一个新的文本
            ClipData clipData = ClipData.newPlainText(null, text);
            clipboardManager.setPrimaryClip(clipData);
        } else {
            Toast.makeText(getContext(), "复制失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 更新本地数据
     */
    private void updateData() {
        // 随机获取本地数据
        Words.NewslistBean bean = beans.get((int) (Math.random() * beans.size()));
        // 改变发送状态
        sendType = !sendType;
        // 设置发送状态
        bean.setSendType(sendType);
        // 添加到数据源的第一条
        list.addFirst(bean);
        // 在第一条插入数据
        adapter.notifyItemInserted(0);
        rvMessageContainer.scrollToPosition(0);
    }

}
